package log

import (
	"fmt"
	"sync"
	"time"
)

var Logger = newDefaultConsoleLogger()

type DefaultConsoleLogger struct {
	entries []*consoleLog
	mu      sync.Mutex
}

type consoleLog struct {
	module  string
	message string
	time    time.Time
}

type IconsoleLogger interface {
	Debug(module string, message string)
	Info(module string, message string)
	Warn(module string, message string)
	Error(module string, message string)
}

func newDefaultConsoleLogger() *DefaultConsoleLogger {
	logger := &DefaultConsoleLogger{}

	go func() {
		for {
			if len(logger.entries) > 0 {
				logger.mu.Lock()

				for _, entry := range logger.entries {
					fmt.Println(fmt.Sprintf("%v : %v By %v", entry.time.Format("2006-01-02 15:04:05"), entry.message, entry.module))
				}

				logger.entries = nil

				logger.mu.Unlock()
			} else {
				time.Sleep(5 * time.Second)
			}
		}
	}()

	return logger
}

/******
debug 日志
*/
func (l *DefaultConsoleLogger) Debug(module string, message string) {
	l.mu.Lock()

	defer l.mu.Unlock()

	log := &consoleLog{
		module:  module,
		message: "\033[33m[Debug]\033[0m " + message,
		time:    time.Now(),
	}

	l.entries = append(l.entries, log)
}

/******
Info 日志
*/
func (l *DefaultConsoleLogger) Info(module string, message string) {
	l.mu.Lock()

	defer l.mu.Unlock()

	log := &consoleLog{
		module:  module,
		message: "\033[34m[INFO]\033[0m " + message,
		time:    time.Now(),
	}

	l.entries = append(l.entries, log)
}

/******
Warn 日志
*/
func (l *DefaultConsoleLogger) Warn(module string, message string) {
	l.mu.Lock()

	defer l.mu.Unlock()

	log := &consoleLog{
		module:  module,
		message: "\033[32m[WARN]\033[0m " + message,
		time:    time.Now(),
	}

	l.entries = append(l.entries, log)
}

/******
Error 日志
*/
func (l *DefaultConsoleLogger) Error(module string, message string) {
	l.mu.Lock()

	defer l.mu.Unlock()

	log := &consoleLog{
		module:  module,
		message: "\033[31m[Error]\033[0m " + message,
		time:    time.Now(),
	}

	l.entries = append(l.entries, log)
}
